<template>
  <div class="container">
    <!-- 固定导航 -->
    <van-nav-bar
      fixed
      left-arrow
      @click-left="$router.back()"
      title="小思同学"
    ></van-nav-bar>

    <!-- 聊天主体区域 -->
    <div class="chat-list">
      <div v-for="(item, index) in list" :key="index">
        <!-- 左侧是机器人小思 -->
        <div class="chat-item left" v-if="item.name === 'xs'">
          <van-image
            fit="cover"
            round
            src="https://img.yzcdn.cn/vant/cat.jpeg"
          />
          <div class="chat-pao">{{ item.msg }}</div>
        </div>

        <!-- 右侧是当前用户 -->
        <div class="chat-item right" v-else>
          <div class="chat-pao">{{ item.msg }}</div>
          <!-- 使用vuex跨组件传图片 -->
          <van-image
            fit="cover"
            round
            :src="$store.state.userPhoto"
          />
        </div>
      </div>
    </div>

    <!-- 对话区域 -->
    <div class="reply-container van-hairline--top">
      <van-field placeholder="说点什么..." v-model.trim="word" v-fofo>
        <template #button>
          <span style="font-size: 12px; color: #999" @click="submit">提交</span>
        </template>
      </van-field>
    </div>
  </div>
</template>

<script>
// 导出 socket.io-client
import { io } from 'socket.io-client'
export default {
  name: 'Chat',
  created () {
    // 进入本页立即与服务器建立连接
    this.socket = io(
      // 建立连接
      'http://geek.itheima.net',
      // 传递参数
      {
        query: { token: this.token },
        // 携带请求头
        transports: ['websocket']
      }
    )
    // 这里监听与服务器连接状况
    this.socket.on('connect', () => {
      console.log('与服务器建立了连接')
    })
    // 接收到服务器返回的信息,将之存于list中
    this.socket.on('message', (data) => {
      this.list.push({
        name: 'xs',
        msg: data.msg
      })
    })
  },
  data () {
    return {
      word: '', // 输入框的内容
      list: [
        // 只根据 name 属性，即可判断出这个消息应该渲染到左侧还是右侧
        { name: 'xs', msg: 'hi，你好！我是小思' },
        { name: 'me', msg: '我是编程小王子' }
      ],
      socket: null
    }
  },
  methods: {
    // 点击提交
    submit () {
      if (this.word.length > 0) {
        console.log(this.word)
        // 提交后追加到list列表中
        this.list.push({ name: 'me', msg: this.word })
        this.socket.emit('message', {
          msg: this.word,
          timestamp: new Date().getTime()
        })
        this.word = ''
      }
    }
  },
  watch: {
    // 侦听 list列表的变化
    list: {
      // 复杂类型使用深度侦听
      deep: true,
      // 在handler 中调用
      handler () {
        // 因为vuedom渲染是异步的,所以这里使用$nextTick 让任务等待真实dom渲染完毕,再执行
        this.$nextTick(() => {
          // 寻找所有.chat-item dom
          const doml = document.querySelectorAll('.chat-item')
          // 滚动到最后一个上
          doml[doml.length - 1].scrollIntoView({
            behavior: 'smooth'
          })
        })
      }
    }
  },
  beforeDestroy () {
    // 组件销毁前关闭连接
    this.socket.close()
    // 清空websocket 实例对象
    this.socket = null
  }
}
</script>

<style lang="less" scoped>
.container {
  height: 100%;
  width: 100%;
  position: absolute;
  left: 0;
  top: 0;
  box-sizing: border-box;
  background: #fafafa;
  padding: 46px 0 50px 0;
  .chat-list {
    height: 100%;
    overflow-y: scroll;
    .chat-item {
      padding: 10px;
      .van-image {
        vertical-align: top;
        width: 40px;
        height: 40px;
      }
      .chat-pao {
        vertical-align: top;
        display: inline-block;
        min-width: 40px;
        max-width: 70%;
        min-height: 40px;
        line-height: 38px;
        border: 0.5px solid #c2d9ea;
        border-radius: 4px;
        position: relative;
        padding: 0 10px;
        background-color: #e0effb;
        word-break: break-all;
        font-size: 14px;
        color: #333;
        &::before {
          content: "";
          width: 10px;
          height: 10px;
          position: absolute;
          top: 12px;
          border-top: 0.5px solid #c2d9ea;
          border-right: 0.5px solid #c2d9ea;
          background: #e0effb;
        }
      }
    }
  }
}
.chat-item.right {
  text-align: right;
  .chat-pao {
    margin-left: 0;
    margin-right: 15px;
    &::before {
      right: -6px;
      transform: rotate(45deg);
    }
  }
}
.chat-item.left {
  text-align: left;
  .chat-pao {
    margin-left: 15px;
    margin-right: 0;
    &::before {
      left: -5px;
      transform: rotate(-135deg);
    }
  }
}
.reply-container {
  position: fixed;
  left: 0;
  bottom: 0;
  height: 44px;
  width: 100%;
  background: #f5f5f5;
  z-index: 9999;
}
</style>
